package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 分页查询商品信息
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> getByPage(@RequestParam("page") int page, @RequestParam("size") int size) {

        Page<Item> result = itemService.page(new Page<>(page, size));
        System.out.println("总条数:" + result.getTotal());
        return new PageDTO<>(result.getTotal(), result.getRecords());
    }

    /**
     * 根据id查询商品信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Item getById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    /**
     * 新增商品
     *
     * @param item
     */
    @PostMapping
    public void saveItem(@RequestBody Item item) {
        System.out.println(item);
        // 基本数据
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(2);//新商品设置默认未上架
        // 新增
        itemService.save(item);

        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_INSERT_KEY, item.getId());
    }

    /**
     * 修改商品状态(是否上架)
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void setItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        itemService.updateStatus(id, status);

    }

    /**
     * 更新商品信息
     * @param item
     */
    @PutMapping
    public void updateItem(@RequestBody Item item) {
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_INSERT_KEY, item.getId());
    }

    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteItemById(@PathVariable("id") Integer id ) {
        itemService.removeById(id);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_DELETE_KEY, id);
    }
}
